package com.totcy.atom.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.totcy.atom.R;
import com.totcy.atom.dialog.ShareDialog;
import com.totcy.atom.utils.WeChatShareUtils;
import com.totcy.baselibrary.utils.LogUtils;
import com.totcy.baselibrary.utils.SPUtil;
import com.totcy.baselibrary.widget.guideview.Component;
import com.totcy.baselibrary.widget.guideview.Guide;
import com.totcy.baselibrary.widget.guideview.GuideBuilder;

import butterknife.BindView;

import static com.totcy.atom.R.id.webView;

/**
 * description: 网页浏览
 *
 * @author : Totcy
 *         date: 2017/11/3 16:56
 *         update: 2017/11/3
 */

public class WebViewActivity extends BaseFullActivity implements Toolbar.OnMenuItemClickListener, View.OnKeyListener {
    @BindView(webView)
    WebView mWebView;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    private static final String FIRST_GUIDE_SHARE = "first_webView_share";

    @Override
    public String getTitleName() {
        return getIntent().getStringExtra("title");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void initView() {
        getToolbarTitleLayout().setNavigationIcon(R.drawable.ic_close_white_24dp);
        //设置右上角菜单
        getToolbarTitleLayout().inflateMenu(R.menu.menu_webview_share);
        getToolbarTitleLayout().setOnMenuItemClickListener(this);

        //WebView设置
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDatabaseEnabled(true);

        //webview在安卓5.0之前默认允许其加载混合网络协议内容
        // 在安卓5.0之后，默认不允许加载http与https混合内容，需要设置webview允许其加载混合网络协议内容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //mWebView.addJavascriptInterface(new JavaMethod(), "nativeMethod");
        mWebView.setDownloadListener(new MyWebViewDownLoadListener());
        mWebView.setWebViewClient(new MyWebViewClient(){});
        mWebView.setWebChromeClient(new MyWebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });
        mWebView.setOnKeyListener(this);
        mWebView.loadUrl(getIntent().getStringExtra("url"));
        //引导层
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                showGuideView();
            }
        });
    }

    @Override
    protected void onDestroy() {
        mWebView.stopLoading();
        mWebView.destroy();
        super.onDestroy();
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            //表示按返回键
            if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                //后退 webView.goForward();//前进
                mWebView.goBack();
                // 已处理
                return true;
            }
        }
        return false;
    }

    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //handler.cancel(); // Android默认的处理方式
            handler.proceed();  // 接受所有网站的证书  解决https拦截问题
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (mProgressBar != null) {
                mProgressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            if (mProgressBar != null) {
                mProgressBar.setVisibility(View.GONE);
            }
            LogUtils.loge(url);
        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mProgressBar != null) {
                mProgressBar.setProgress(newProgress);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!WebViewActivity.this.isDestroyed()) {
                setTitle(title);
            }
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {

        new ShareDialog(this).setOnItemClick(new ShareDialog.OnShareTypeClick() {
            @Override
            public void onItemType(int type) {
                WeChatShareUtils weChatShareUtils = new WeChatShareUtils(WebViewActivity.this);
                weChatShareUtils.shareUrl(
                        mWebView.getUrl(),
                        "",
                        mWebView.getTitle(),
                        type);
            }
        }).showDialog();
        return true;
    }

    /**
     * 创建引导层
     */
    private void showGuideView() {
        boolean firstLook = (boolean) SPUtil.get(this, FIRST_GUIDE_SHARE, true);
        if (!firstLook) {
            return;
        }
        Guide guide = new GuideBuilder()
                .setTargetView(getToolbarTitleLayout())
                .setAlpha(150)
                //.setHighTargetCorner(10)
                //.setHighTargetPadding(5)
                .setOverlayTarget(false)
                .setOutsideTouchable(false)
                .setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
                    @Override
                    public void onShown() {
                    }

                    @Override
                    public void onDismiss() {
                        SPUtil.put(WebViewActivity.this, FIRST_GUIDE_SHARE, false);
                    }
                })
                .addComponent(new SimpleComponent())
                .createGuide();
        guide.setShouldCheckLocInWindow(false);
        guide.show(this);

    }

    private class SimpleComponent implements Component {

        @Override
        public View getView(LayoutInflater inflater) {
            View view = inflater.inflate(R.layout.guide_layout_right, null);
            TextView textView = view.findViewById(R.id.tv_guideMsg);
            textView.setText(R.string.click_to_share);
            return view;
        }

        @Override
        public int getAnchor() {
            return Component.ANCHOR_BOTTOM;
        }

        @Override
        public int getFitPosition() {
            return Component.FIT_END;
        }

        @Override
        public int getXOffset() {
            return -5;
        }

        @Override
        public int getYOffset() {
            return 10;
        }
    }
}
